<?php


namespace app\common\service;


use AlibabaCloud\SDK\Green\V20220302\Models\TextModerationPlusRequest;
use AlibabaCloud\Tea\Exception\TeaUnableRetryError;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
use AlibabaCloud\SDK\Green\V20220302\Green;
use think\facade\Env;
class TextCheckService
{
    public $client;

    public function __construct()
    {
        $config = new Config([
            /**
             * 阿里云账号AccessKey拥有所有API的访问权限，建议您使用RAM用户进行API访问或日常运维。
             * 强烈建议不要把AccessKey ID和AccessKey Secret保存到工程代码里，否则可能导致AccessKey泄露，威胁您账号下所有资源的安全。
             * 常见获取环境变量方式：
             * 获取RAM用户AccessKey ID：getenv("ALIBABA_CLOUD_ACCESS_KEY_ID");
             * 获取RAM用户AccessKey Secret：getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET");
             */
            "accessKeyId" => Env::get('aliyun_word_check.access_key_id'),
            "accessKeySecret" => Env::get('aliyun_word_check.access_key_secret'),
            // 设置HTTP代理。
            // "httpProxy" => "http://10.10.xx.xx:xxxx",
            // 设置HTTPS代理。
            // "httpsProxy" => "https://10.10.xx.xx:xxxx",
            "endpoint" => Env::get('aliyun_word_check.endpoint'),
            "regionId" => Env::get('aliyun_word_check.region_id'),

        ]);
        // 注意，此处实例化的client请尽可能重复使用，避免重复建立连接，提升检测性能。
        $this->client = new Green($config);
    }

    public function checkWord($word_str)
    {
        $request = new TextModerationPlusRequest();
        $request->service = "llm_query_moderation";
        $serviceParameters = array("content" => $word_str);

        $request->serviceParameters = json_encode($serviceParameters);

        $runtime = new RuntimeOptions();
        $runtime->readTimeout = 6000;
        $runtime->connectTimeout = 3000;

        try {
            $response = $this->client->textModerationPlusWithOptions($request, $runtime);
            if (200 != $response->statusCode) {
                //print_r("response not success. code:" . $response->statusCode);
                return [
                    'code'=>-1,
                    'data'=>[],
                    'msg'=>'通信失败',
                ];
            }
            $body = $response->body;
            //print_r("requestId = " . $body->requestId . "\n");
            //print_r("code = " . $body->code . "\n");
            //print_r("message = " . $body->message . "\n");
            if (200 != $body->code) {
                //print_r("text moderation not success. code:" . $body->code);
                return [
                    'code'=>2,
                    'data'=>[
                        'requestId'=>$body->requestId,
                        'code'=>$body->code,
                    ],
                    'msg'=>$body->message,
                ];
            }
            $data = $body->data;

            if(empty($data->result[0]->confidence))
            {
                return [
                    'code'=>1,
                    'data'=>[
                        'requestId'=>$body->requestId,
                        'code'=>$body->code,
                        'data'=>$data,
                    ],
                    'msg'=>$data->result[0]->description,
                ];
            }
            else
            {
                return [
                    'code'=>0,
                    'data'=>[
                        'requestId'=>$body->requestId,
                        'code'=>$body->code,
                        'data'=>$data,
                    ],
                    'msg'=>$data->result[0]->description,
                ];
            }
            //print_r("data = " . json_encode($data));
        } catch (TeaUnableRetryError $e) {
//            var_dump($e->getMessage());
//            var_dump($e->getErrorInfo());
//            var_dump($e->getLastException());
//            var_dump($e->getLastRequest());
            return [
                'code'=>-1,
                'data'=>[],
                'msg'=>'通信异常',
            ];
        }
    }
}